package com.ezcoding.dao;

import com.ezcoding.model.FinanceItem;
import com.ezcoding.model.Message;
import com.jfinal.plugin.activerecord.Db;

import java.util.List;

public class FinanceDao {
    public static FinanceDao dao = new FinanceDao();

    public List<FinanceItem> getFinanceItems(String companyId) {
        String sql = Db.getSql("Finance.getFinanceItems");

        return FinanceItem.dao.find(sql, companyId);
    }

    public FinanceItem getFinanceItem(String companyId, String itemId) {
        String sql = Db.getSql("Finance.getFinanceItemById");

        return FinanceItem.dao.findFirst(sql, companyId, itemId);
    }

    private List<Message> getFinanceMessages(
            String username,
            int minType,
            int maxType,
            String startDate,
            String endDate) {
        String sql = Db.getSql("Finance.getFinanceMessages");

        return Message.dao.find(sql, username, minType, maxType, startDate, endDate);
    }

    public List<Message> getFinanceMessages(
            String username,
            int type,
            String startDate,
            String endDate) {
        if (type == 0) {
            return getFinanceMessages(
                    username,
                    Message.MESSAGE_TYPE_TICKET_OUT,
                    Message.MESSAGE_TYPE_TICKET_ADJUST,
                    startDate,
                    endDate);
        } else {
            return getFinanceMessages(
                    username,
                    Message.MESSAGE_TYPE_PRODUCTBATCH,
                    Message.MESSAGE_TYPE_TAXRATECHANGE,
                    startDate,
                    endDate);
        }
    }

    public List<Message> getFinanceMessagesByType(
            String username,
            int type,
            String startDate,
            String endDate) {
        String sql = Db.getSql("Finance.getFinanceMessagesByType");

        return Message.dao.find(sql, username, type, startDate, endDate);
    }

    public boolean updateFinanceDirectory(
            String companyId,
            int type,
            String oldDirectory,
            String newDirectory) {
        String sql = Db.getSql("Finance.getFinanceItemByCompanyIdAndCategory");

        List<FinanceItem> financeItems = FinanceItem.dao.find(sql, companyId, type, oldDirectory);

        for (FinanceItem financeItem : financeItems) {
            financeItem.setCategory(newDirectory);
            if (!financeItem.update()) {
                return false;
            }
        }

        return true;
    }

    public long getFinanceItemsCount(
            String companyId,
            int financeType,
            String category) {
        String sql = Db.getSql("Finance.getFinanceItemsCount");

        return Db.queryLong(sql, companyId, financeType, category);
    }
}
